from fastapi import APIRouter, Query
from tortoise.expressions import Q

from app.models import CustomerUser
from app.models.mini import MiniAuditLog

from app.schemas import SuccessExtra
from app.schemas.apis import *
from app.core.dependency import DependPermisson

mini_log_router = APIRouter()

@mini_log_router.get('/list', summary="审计日志", dependencies=[DependPermisson])
async def get_audit_log_list(
    page: int = Query(1, description="页码"),
    page_size: int = Query(10, description="每页数量"),
    username: str = Query("", description="操作人名称"),
    module: str = Query("", description="功能模块"),
    summary: str = Query("", description="接口描述"),
    start_time: str = Query("", description="开始时间"),
    end_time: str = Query("", description="结束时间"),
):

    q = Q()
    search_user_ids = []
    if username:
        search_users = await CustomerUser.filter(name__contains=username).values("id")
        search_user_ids = {orders['id'] for orders in search_users}  # 获取所有的 user_id
    if search_user_ids:
        q &= Q(user_id__in=search_user_ids)
    if module:
        q &= Q(module__icontains=module)
    if summary:
        q &= Q(summary__icontains=summary)
    if start_time and end_time:
        q &= Q(created_at__range=[start_time, end_time])
    elif start_time:
        q &= Q(created_at__gte=start_time)
    elif end_time:
        q &= Q(created_at__lte=end_time)
        
    audit_log_objs = await MiniAuditLog.filter(q).offset((page - 1) * page_size).limit(page_size).order_by("-created_at")
    total = await MiniAuditLog.filter(q).count()
    data = [await audit_log.to_dict() for audit_log in audit_log_objs]

    user_ids = {logs['user_id'] for logs in data}  # 获取所有的 user_id
    users = await CustomerUser.filter(id__in=user_ids)
    users_dict = {user.id: user.name for user in users}


    for audit_log_obj in data:
        if not audit_log_obj['username']:
            audit_log_obj['username'] = users_dict.get(audit_log_obj['user_id'], "游客")
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)
